requireJS(['constant', 'site', 'handlebars', 'public', 'static/js/page/common/common.js'], function (Constant, site, Handlebars, Public, Common) {
    Public.initProductSearch();
    Constant.initHandlebars(Handlebars);
    // 列表

    var url = {
        getActivitiProccessImage: "manager/getActivitiProccessImage.do",
        contractBatchDownload: "manager/contractBatchDownload.do",
        selectLoanMethodList: "manager/selectLoanMethodList.do",
    }


    //渲染搜索框的贷款方式
    site.send({
        url: url.selectLoanMethodList,
        callback: function (data) {
            data = JSON.parse(data);
            if (data.type == '1') {
                var source = $("#loanMethod_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = data
                var html = template(list)
                $('#loan_way').append(html);
            }
        }
    })

    var frontData = {pageNum: 1, state: 1};
    var orderBreachData = {};
    var allDownLoadData = {};
    var product_id, order_id, task_id;

    var init = function () {
//头部日期
        site.send({
            url: "manager/selectApplyTermList.do",
            // async:false,
            data: {},
            callback: function (data) {
                var list = JSON.parse(data)
                if (list.type == '1') {
                    var template2 = Handlebars.compile($("#history_head_date_tpl").html())
                    var html2 = template2(list)
                    $("#history_head_date").html(html2)
                } else {
                    Constant.fn.Message('F'.list.msg)
                }
            }
        })
        site.send({
            url: "manager/queryOrderContractsList.do",
            //async:false
            data: frontData,
            callback: function (data) {
                var list = JSON.parse(data)
                if (list.type == '1') {
                    $("#total").text(list.content.total)

                    var template = Handlebars.compile($("#history_content_tpl").html())

                    var menuIndex = getAurlparam('h') || 0;
                    var thirdMenusIndex = getAurlparam('t') || 0;
                    var leftIndex = getAurlparam('i') || 0;

                    var storageContent = JSON.parse(localStorage.getItem('content'));

                    var obj = {
                        content: list,
                        fourthMenus: storageContent.menus[menuIndex].children[leftIndex].children[thirdMenusIndex].children || {}
                    }


                    var html = template(obj)
                    $("#history_content").html(html)
                    // 分页
                    $('.historyList-page-container').createPager({
                        current: frontData.pageNum,
                        total: list.content.total,
                        pageSize: list.content.pageSize,
                        needInput: false,
                        backFn: function (current) {
                            frontData.pageNum = current;
                            init();
                        }
                    })
                    onBindFun();

                    Public.record('t_order_public');
                } else {
                    Constant.fn.Message('F', list.msg);
                }
            }
        })

    }
    init();

    function onBindFun() {
        $(".orderBreachSelect").on('change', function () {
            product_id = $(this).data('productid');
            order_id = $(this).data('id')
            var obj = $(this).find('option:selected');
            if (obj.val() == 'checkOrder') {
                pjaxGo('loanIng/contractManager/detail.html?order_id=' + order_id + "&product_id=" + product_id);
            }
            if (obj.val() == 'historySeveralDownload') {
                allDownLoadData.oid = order_id;
                allDownLoad();
            }
            if (obj.val() == 'orderBreak') {
                $(".orderBreachWinBox").show();
                $("#breachMoneyText").val('')
                orderBreachData.oid = order_id;
                bbcCost();
            }
            if (obj.val() == 'lookProcess') {
                $('.processBox').remove()
                site.send({
                    url: url.getActivitiProccessImage,
                    data: {
                        taskId: task_id,
                    },
                    callback: function (data) {
                        data = JSON.parse(data)
                        if (data.type == 1) {
                            var source = $("#process_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data.content
                            var html = template(list)
                            $('.lookProcess').append(html)
                            $('.lookProcess_winBox').toggle();
                        } else {
                            Constant.fn.Message("F", data.msg);
                        }
                    }
                })
                //queryDelegate(1);
            }
            if (obj.val() == 'submitVisit') {
                Common.visit(order_id);
                Common.init(3,order_id);
            }
            $(this).val('-1')
        })
        //拿到所有的复选框，当有复选框没选上的时候,取消全选
        $("input:checkbox[name='ch_id']").on('click', function () {
            var checkboxs = $("input:checkbox[name='ch_id']");
            var sum = 0;
            var length = checkboxs.length;
            $.each(checkboxs, function (i, checkbox) {
                if ($(checkbox).prop("checked")) {
                    sum++;
                }
            })
            if (sum == length) {
                $('.all_checked').prop("checked", true);
            } else {
                $('.all_checked').prop("checked", false);
            }
        })
        // 全选
        $(".all_checked").click(function () {
            $("input[name='ch_id']").prop('checked', $(this).prop('checked'))
        })

        function bbcCost() {
            site.send({
                url: "manager/aOfBOf.do",
                //async:false
                data: {},
                callback: function (data) {
                    var list = JSON.parse(data);
                    $("#breachMoney").val(list.content.bbc_cost);
                }
            })
        }

        //批量操作下载合同select
        $("#allDown_select").on('change', function () {
            var data = ''
            var selected = $(this).find("option:selected");
            $(this).find("option:first").prop("selected", false).prop("selected", true);
            $("input[name='ch_id']:checked").each(function (index, item) {
                data = data + $(item).val() + ","
            })
            data = data.substring(0, data.length - 1)
            if (selected.val() == '下载合同') {
                //删除产品
                if (!data) {
                    Constant.fn.Message('I', "未选择要下载的订单")
                    return;
                }
                //$('.delete_winBox').toggle();

                //$('.sureDel').on('click', function () {

                $('.prog-c').css('width', '0px');
                $('.prog-rate i').text('0');
                $('.package_winBox').show();
                $('.downloaded').hide();
                $('.downloading').show();

                //进度条
                var time = 0;
                var prog = 0;
                var timer = setInterval(function () {
                    time += 3;
                    prog += 11;
                    $('.prog-c').css('width', prog + 'px')
                    $('.prog-rate i').text(time);
                    if (time == 99) {
                        clearInterval(timer);
                    }
                }, 5)


                site.send({
                    url: url.contractBatchDownload,
                    data: {
                        oid: data
                    },
                    callback: function (data) {
                        data = JSON.parse(data)
                        if (data.type == 1) {
                            //$('.delete_winBox').toggle();
                            $.each(data.content.zipMap, function (i, e) {
                                window.open(e.zipUrl);
                            })

                            var source = $("#detail_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var html = template(data.content);
                            $("#detail_list").html(html);
                            Constant.fn.Message('T', data.msg);

                            //time = 100;
                            $('.prog-c').css('width', '376px');
                            $('.downloaded').show();
                            $('.downloading').hide();

                            //pjaxReload();
                        } else {
                            $('.package_winBox').hide();
                            Constant.fn.Message("F", data.msg)
                        }
                    },
                    callError: function () {

                    }
                })
                //})
            }
        })

    }

    //日期控件
    $(".datepicker").datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true
    })


    //列表条件搜索
    $("#historySeach").on('click', function () {
        frontData = {
            pageNum: 1,
            state: 1
        }
        if ($("#PoInput-formDate").val() != '') {
            frontData.beginTime = $("#PoInput-formDate").val();//开始时间
        }
        if ($("#PoInput-toDate").val() != '') {
            frontData.endTime = $("#PoInput-toDate").val();//结束时间
        }
        if ($("#seleNames").val() != '') {
            frontData.type = $("#seleNames").val();//字段
        }
        if ($("#inputNames").val() != '' && $("#inputNames").val().trim()) {
            frontData.keyword = $("#inputNames").val();//keybord
        }
        if ($("#history_headSelect").val() != '') {
            frontData.atId = $("#history_headSelect").val();//分期id
        }
        if ($("#loan_way").val() != '') {
            frontData.loan_way = $("#loan_way").val();
        }
        if ($("#product_choose_list").val()) {
            frontData.product_id = $("#product_choose_list").val()
        }
        init();
    })

    $("#breachCommit").click(function () {
        orderBreachData.renege_money = $("#breachMoney").val();
        orderBreachData.remarks = $("#breachMoneyText").val();
        site.send({
            url: "manager/orderBreachContract.do",
            //async:false
            data: orderBreachData,
            callback: function (data) {
                var list = JSON.parse(data)
                if (list.type == '1') {
                    $(".orderBreachWinBox").hide();
                    Constant.fn.Message('T', list.msg);
                    pjaxReload();
                } else {
                    Constant.fn.Message('F', list.msg);
                }
            }
        })
    })

    // 批量下载
    function allDownLoad() {

        $('.prog-c').css('width', '0px');
        $('.prog-rate i').text('0');
        $('.package_winBox').show();
        $('.downloaded').hide();
        $('.downloading').show();

        //进度条
        var time = 0;
        var prog = 0;
        var timer = setInterval(function () {
            time += 3;
            prog += 11;
            $('.prog-c').css('width', prog + 'px')
            $('.prog-rate i').text(time);
            if (time == 99) {
                clearInterval(timer);
            }
        }, 5)


        site.send({
            url: url.contractBatchDownload,//
            // async: false,
            data: allDownLoadData,
            callback: function (data) {
                var list = JSON.parse(data);
                if (list.type == 1) {
                    //downloadFile(list.content.zipUrl)
                    $.each(list.content.zipMap, function (i, e) {
                        window.open(e.zipUrl);
                        /*var req = new XMLHttpRequest();
                        req.onprogress = function(evt){
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                console.log(percentComplete);
                            } else {
                                // Unable to compute progress information since the total size is unknown
                            }
                        };
                        req.open("GET", e.zipUrl);
                        req.send();*/
                        /*$.ajax({
                            url: e.zipUrl,
                            crossDomain: true,
                            xhrFields: {
                                withCredentials: true
                            },
                            headers: {'Access-Control-Allow-Origin': "*"},
                            //dataType: 'jsonp',
                            progress: function (evt) {
                                if (evt.lengthComputable) {
                                    var percentComplete = evt.loaded / evt.total;
                                    console.log(percentComplete);
                                } else {
                                    // Unable to compute progress information since the total size is unknown
                                }
                            },
                            success: function (data) {
                                console.log(data)
                            }
                        })*/
                    })

                    var source = $("#detail_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(list.content);
                    $("#detail_list").html(html);

                    Constant.fn.Message("T", list.msg);
                    //time = 100;
                    $('.prog-c').css('width', '376px');
                    $('.downloaded').show();
                    $('.downloading').hide();

                    //$('.package_winBox').();
                } else {
                    $('.package_winBox').hide();
                    Constant.fn.Message('F', list.msg)
                }
            }
        })
    }

    /*//下载合同方法
    function downloadFile(src) {
        var $a = document.createElement('a');
        $a.setAttribute("href", src);
        $a.setAttribute("download", "");
        var evObj = document.createEvent('MouseEvents');
        evObj.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
        $a.dispatchEvent(evObj);
    };*/

})